package com.czh.controller;

import com.czh.domain.ResponseResult;
import com.czh.domain.entity.LoginUser;
import com.czh.domain.entity.Menu;
import com.czh.domain.entity.User;
import com.czh.domain.vo.AdminInfoVo;
import com.czh.domain.vo.RoutersVo;
import com.czh.domain.vo.UserInfoVo;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.hander.exception.SystemException;
import com.czh.service.AdminLoginService;
import com.czh.service.MenuService;
import com.czh.service.RoleService;
import com.czh.utils.BeanCopyUtils;
import com.czh.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 后台登录控制器
 */
@RestController
@Tag(name = "AdminLoginController",description = "后台登录控制器相关API")
public class AdminLoginController {
    @Resource
    private AdminLoginService adminLoginService;
    @Resource
    private MenuService menuService;
    @Resource
    protected RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult<Map<String,String>> login(@RequestBody User user) {
        if (user.getUserName() == null || user.getPassword() == null) {
            throw new SystemException(AppHttpCodeEnum.PARAM_INVALID);
        }
        return adminLoginService.login(user);
    }

    //管理员登出
    @PostMapping("/user/logout")
    public ResponseResult<Object> logout() {
        return adminLoginService.logout();
    }

    //获取管理员信息
    @Operation(summary = "获取管理员信息",description = "权限信息，角色信息，个人信息")
    @GetMapping("/getInfo")
    public ResponseResult<AdminInfoVo> getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long id = loginUser.getUser().getId();
        //权限信息
        List<String> perms = menuService.selectPermsByUserId(id);
        //角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(id);

        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        return ResponseResult.okResult(new AdminInfoVo(perms,roleKeyList,userInfoVo));
    }
    //上面获取到管理员信息后根据信息返回管理员对应的菜单
    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        return ResponseResult.okResult(new RoutersVo(menus));
    }
}

